<?php
/**
 * 自定义数学计算相关方法 
 * 
 * Created		: 2011-06-14
 * Modified		: 2011-07-06 
 * @link		: http://www.qixbo.com
 * @copyright	: [Qixbo.Com] (c) 2011
 * @version		: 0.2.0
 * @author		: Joseph Chen (jsph.chen@gmail.com)
 * @see			: http://blog.xe28.tk/archives/188/
 */
class Url
{
	public static $urlPattern = '~(https?://[\w\./\?\#\=\&\-]+)~';
	
	/**
	 * 判断字符串中是否包含有URL链接
	 * @param string $str
	 */
	public static function containUrl($str)
	{
		return preg_match(self::$urlPattern, $str);
	}
	
	/**
	 * 获取字符串中的URL链接
	 * @param string $str
	 */
	public static function getUrlsFromStr($str)
	{
		preg_match_all(self::$urlPattern, $str, $matches);
		if (!empty($matches[1])) {
			return $matches[1];
		} else {
			return false;
		}
	}
	
	/**
	 * CURL方式获取网页源代码
	 * @param string $url
	 */
	public static function getContents($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}
	
	/**
	 * 自动给URL加上链接
	 * @param string $str
	 */
	public static function addLink($str)
	{
		return preg_replace(self::$urlPattern, '<a href="$1" target="_blank">$1</a>', $str);
	}
	
	/**
	 * 网址缩短
	 * @param string $url 要缩短的网址
	 * @param string $doType 操作类型:
	 * 	1-将网址缩写,保存并返回缩写字符串
	 *  2-返回网址缩写
	 */
	public static function short($url, $doType=1)
	{
		$url = trim($url);
		$short = Db::read('qxb_url_ab', $url, 'url', 'short');
		
		if ($short) {
			return $short;
		}
		
		$hex = md5($url);
		
		$tmp = array();
		
		for ($i=0; $i<4; $i++) {
			$subHex = substr($hex, $i*8, 8);
			$out = MMath::dec2Any(hexdec($subHex), 62);
			$_url = Db::read('qxb_url_ab', $out, 'short', 'url');
			if ($_url) {
				$out = '';
				$tmp[] = $subHex;
				continue;
			} else {
				break;
			}
		}
		
		
		if (!$out) {// 机率应该很小吧?
			for ($i=1; $i<24; $i++) {
				if ($i%8 == 0) continue;// 已经在前面循环过,得不到结果了
				$subHex = substr($hex, $i, 8);
				if (in_array($subHex, $tmp)) continue;
				$out = MMath::dec2Any(hexdec($subHex), 62);
				$url = Db::read('qxb_url_ab', $out, 'short', 'url');
				if ($url) {
					$out = '';
					continue;
				} else {
					break;
				}
			}
		}
		
		// 还会存在得不到缩写的情况?
		if ($out) {
			$data = array(
				'short'	=> $out,
				'url'	=> $url
			);
			Db::insert('qxb_url_ab', $data);
		}
		return $out;
	}
	
	
}
